package com.ekingstar.framework.service.impl;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.ui.WebAuthenticationDetails;

import com.ekingstar.framework.domain.SystemLog;
import com.ekingstar.framework.domain.User;
import com.ekingstar.framework.security.UserUtil;
import com.ekingstar.framework.service.ISystemLogService;
import com.ekingstar.framework.util.HibernateCallbackUtil;
import com.ekingstar.framework.util.Page;
import com.ekingstar.framework.util.Utility;
	
public class SystemLogServiceImpl implements ISystemLogService{
	
	private static Logger log = LoggerFactory.getLogger(SystemLogServiceImpl.class);
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
	private HibernateTemplate hibernateTemplate;
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void addLog(String str) {
		
	}

	public void addLog(SystemLog systemLog) {
		this.hibernateTemplate.save(systemLog);
	}

	public void addLoginLog(SystemLog systemLog) {
		this.hibernateTemplate.save(systemLog);
	}
	
	public void addLoginLog(SystemLog systemLog, User user) {

	}

	public List<SystemLog> getSystemLogList() {
		return this.hibernateTemplate.find("from SystemLog");
	}
	
	public Page getSystemLogPage(SystemLog systemLog, int pageNo, int pageSize) {
		if (pageNo <= 0) pageNo = 1;
		//StringBuffer sb = new StringBuffer("" +
		//		"select u.name, s.type from User as u ,SystemLog as s where s.userId = u.id ");
		StringBuffer sb = new StringBuffer("" +
			"select a.name as userId,b.model_name as modelName, b.type as type, b.time as time, b.ip as ip, b.description as description" +
			" from t_system_log b " +
			" left join t_user a on b.user_Id = a.id where 1 = 1");
		Map params = new HashMap();
		Map scalars = new HashMap();
		scalars.put("userId", Hibernate.STRING);
		scalars.put("type", Hibernate.STRING);
		scalars.put("time", Hibernate.TIMESTAMP);
		scalars.put("ip", Hibernate.STRING);
		scalars.put("description", Hibernate.STRING);
		scalars.put("modelName", Hibernate.STRING);
		
		if (systemLog != null){
			if (systemLog.getType() != null && !systemLog.getType().trim().equals("")){
				sb.append(" and b.type like :type");
				params.put("type", ""+systemLog.getType().trim()+"");
			}
			if (systemLog.getName() != null && !systemLog.getName().trim().equals("")){
				sb.append(" and a.name like :name");
				params.put("name", "%"+systemLog.getName().trim()+"%");
			}
			if (systemLog.getModelName() != null && !systemLog.getModelName().trim().equals("")){
				sb.append(" and b.model_name = :mn");
				params.put("mn", systemLog.getModelName().trim());
			}
			if (systemLog.getBeginDate() != null && !systemLog.getBeginDate().equals("")){
				Date date;
				try {
					date = sdf.parse(systemLog.getBeginDate().trim());
					sb.append(" and b.time >= :beginDate");
					params.put("beginDate", date);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				}
				
				
			}
			if (systemLog.getEndDate() != null && !systemLog.getEndDate().equals("")){
				Date date;
				try {
					date = sdf.parse(systemLog.getEndDate().trim());
					date.setDate(date.getDate()+1);
					sb.append(" and b.time <= :endDate");
					params.put("endDate", date);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				}
			}
		}
		/*int s_length = sb.length();
		String sql = "";
		String b_and = sb.substring(s_length-3,s_length);
		if(b_and.equals("and")){
			sql = sb.substring(0,s_length-3);
		}
		sb = new StringBuffer(sql);*/
		
		sb.append(" order by b.time desc ");
		//HibernateCallback action = HibernateCallbackUtil.getNativeCallbackWithPage(sb, params,scalars,null, pageNo, pageSize);
		HibernateCallback action = HibernateCallbackUtil.getNativeCallbackWithPage(sb, params,scalars,Transformers.aliasToBean(SystemLog.class), pageNo, pageSize);
		Page page = (Page)hibernateTemplate.execute(action);
		return page;
		
		
	}

	public List getSystemLogTypeList() {
		StringBuffer sb = new StringBuffer("select a.type from SystemLog as a group by a.type");
		return this.hibernateTemplate.find(sb.toString());
	}

	public void logBizLog(String modelName,String msg) {
		// TODO Auto-generated method stub
		Authentication au = SecurityContextHolder.getContext().getAuthentication();
		WebAuthenticationDetails detail = (WebAuthenticationDetails) au.getDetails();
		SystemLog log = new SystemLog();
		log.setDescription(msg);
		log.setIp(detail.getRemoteAddress());
		log.setName(UserUtil.getCurrentUserId());
		log.setTime(new Date());
		log.setType(SystemLog.LogType.biz.name());
		hibernateTemplate.save(log);
		
	}

	public boolean isUserLastLoginIp(final String userId) {
		/*List list =  this.hibernateTemplate.findByNamedParam("select ip from SystemLog a where a.type='login' and " +
				" a.userId=:userId order by a.time desc", "userId", userid);*/
		List list = (List) this.hibernateTemplate.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				StringBuffer sb = new StringBuffer("select ip from SystemLog a where a.type='login' and " +
				" a.userId=:userId order by a.time desc");
				Query query = session.createQuery(sb.toString());
				query.setString("userId", userId);
				query.setFirstResult(0);
				query.setMaxResults(2);
				return query.list();
			}
		});
		if(!Utility.isEmpty(list) && list.size()==2){
			String thisLoginIp = list.get(0).toString();
			String lastLoginIp = list.get(1).toString();
			if(thisLoginIp.equals(lastLoginIp)) return true;
		}
		
		return false;
	}
	
}
